﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Drawing;
using System.Runtime.InteropServices;

using DNA;
using TJADRICD.CollaborativeDesignPlugin.Form;
using TJADRICD.CollaborativeDesignPlugin.Function;
using TJADRICD.CollaborativeDesignPlugin.Commission;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.DatabaseServices;
using Autodesk.AutoCAD.EditorInput;
using Autodesk.AutoCAD.Geometry;
using Autodesk.AutoCAD.ApplicationServices;
using DBTransMan = Autodesk.AutoCAD.DatabaseServices.TransactionManager;
using Application = Autodesk.AutoCAD.ApplicationServices.Application;


namespace TJADRICD.CollaborativeDesignPlugin.Form
{
    public partial class SignControl : System.Windows.Forms.Form
    {

        public SignControl()
        {
            InitializeComponent();
            this.WindowState = FormWindowState.Maximized;
        }

        string signer;
        DrawingTree dt = new DrawingTree();
        CheckCompetence checkCompetence = new CheckCompetence();
        bool checkedInitialing = false;
        List<Competence> signerCompetence = new List<Competence>();
        public String userID = "121";
        public String userName;
        struct Pair
        {
            public string fileName;
            public FileStream fs;
            public Pair(string fileName, FileStream fs)
            {
                this.fileName = fileName;
                this.fs = fs;
            }
        }
        List<Pair> locks = new List<Pair>();

        public void signControlLoad(String signFileName)
        {
            foreach (string webPath in Config.ProjectPath)
            {
                DirectoryInfo Dir_Web = new DirectoryInfo(webPath);
                DirectoryInfo[] Dir_Pros = Dir_Web.GetDirectories();
                foreach (DirectoryInfo Dir_Pro in Dir_Pros)
                {
                    if ((Dir_Pro.Name == "Sign") || (Dir_Pro.Name == "TK"))
                    {
                        continue;
                    }
                    this.cb_ProNo.Items.Add(Dir_Pro.Name);
                }
            }

            bool flag = false;
            try
            {
                signer = null;
                StringBuilder name = new StringBuilder(1024);

                int status = -3;
                status = Function_Verify.TJAD_SIGN_ReadName(signFileName, name);
                if (status == 0)
                {
                    MessageBox.Show(name.ToString());
                    signer = name.ToString();
                    Tools.WriteMessageWithReturn("签名人:" + signer);
                    lblSigner.Text = signer;
                    CommissionName.Text = signer;
                    flag = true;
                }
                else
                {
                    MessageBox.Show("读取VRF文件" + signFileName + "失败" + "   出错编号" + status.ToString());
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show("读取用户文件发生异常" + ex.Message + ex.StackTrace);
            }
            if (!flag)
            {
                this.Close();
            }
        }

        private void SignControl_Load(object sender, EventArgs e)
        {
            //foreach (string webPath in Config.ProjectPath)
            //{
            //    /*                MessageBox.Show(webPath);*/
            //    DirectoryInfo Dir_Web = new DirectoryInfo(webPath);
            //    DirectoryInfo[] Dir_Pros = Dir_Web.GetDirectories();
            //    foreach (DirectoryInfo Dir_Pro in Dir_Pros)
            //    {
            //        if ((Dir_Pro.Name == "Sign") || (Dir_Pro.Name == "TK"))
            //        {
            //            continue;
            //        }
            //        this.cb_ProNo.Items.Add(Dir_Pro.Name);
            //    }
            //}

            bool flag = false;
            try
            {
                signer = null;
                StringBuilder name = new StringBuilder(1024);
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.InitialDirectory = Config.HandwritingPath;
                ofd.Filter = "签名验证文件 (*.vrf)|*.vrf|所有文件|*.*";
                ofd.FilterIndex = 1;

                if (ofd.ShowDialog() == DialogResult.OK)
                {
                   int status = -3;
                    status = Function_Verify.TJAD_SIGN_ReadName(ofd.FileName, name);
                   if (status == 0)
                   {
                        signer = name.ToString();
                        Tools.WriteMessageWithReturn("签名人:" + signer);
                        userName = signer;
                        lblSigner.Text = signer;
                        flag = true;
                    }
                    else
                    {
                        MessageBox.Show("读取VRF文件" + ofd.FileName + "失败" + "   出错编号" + status.ToString());
                    }
                }

                dt.ReadDBUDC(userID);
                checkCompetence.InitComStr();
                dt.DBToUDCList();
                foreach (UDCUserID uID in dt.udcList)
                {
                    this.cbsigner.Items.Add(uID.userName);
                    //MessageBox.Show(uID.userName.Length.ToString()+"test");
                    //MessageBox.Show(uID.userName);
                }
                //  else
                //  {
                //MessageBox.Show("读取失败2");
                //   }
                //                int status = TJAD_iKey_ReadName(name);
                //                Tools.WriteMessageWithReturn(status.ToString());
                //                if (status == 0)
                //                {
                //                    signer = name.ToString();
                //                    Tools.WriteMessageWithReturn("签名人:" + signer);
                // 
                //                    lblSigner.Text = signer;
                //                    flag = true;
                //                }
                //                else
                //                {
                //                    
                //                }
                //signer = "李刚";



            }
            catch (System.Exception ex)
            {
                MessageBox.Show("读取用户文件发生异常" + ex.Message + ex.StackTrace);
            }
            if (!flag)
            {
                this.Close();
            }
        }


        private void btnOK_Click(object sender, EventArgs e)
        {
            UnLockAllFiles();
            try
            {
                if (signer == null)
                {
                    //MessageBox.Show("请选择签名者！");
                    //btnSelectSigner.PerformClick();
                    if (signer == null)
                        return;
                }
                Editor ed = Tools.Editor;
                for (int i = 0; i < dataGridView.Rows.Count; i++)
                {
                    DataGridViewRow row = dataGridView.Rows[i];
                    bool needSign = false;
                    bool needUnsign = false;
                    List<string> signItems = new List<string>();
                    List<string> unsignItems = new List<string>();
                    int approvedByIndex = dataGridView.Columns.IndexOf(dataGridView.Columns["ApprovedBy"]);
                    int ELV3Index = dataGridView.Columns.IndexOf(dataGridView.Columns["ELV3"]);
                    int CTBIndex = dataGridView.Columns.IndexOf(dataGridView.Columns["FileName"]);
                    for (int j = approvedByIndex; j <= ELV3Index; j++)
                    {
                        if (j == CTBIndex)
                        {
                            continue;
                        }
                        DataGridViewCell cell = row.Cells[j];
                        if (row.Cells[j].FormattedValue.ToString() != ""
                            && row.Cells[j].Style.BackColor == Color.LightGreen
                            && row.Cells[j].Value.ToString() == signer)
                        {
                            signItems.Add(dataGridView.Columns[j].Name);
                            needSign = true;
                        }
                        if (row.Cells[j].Value.ToString() == ""
                            && row.Cells[j].Style.BackColor == Color.LightGreen)
                        {
                            unsignItems.Add(dataGridView.Columns[j].Name);
                            needUnsign = true;
                        }
                    }
                    if (needSign || needUnsign)
                    {
                        string fileName = dataGridView.Rows[i].Cells["FileName"].Value.ToString();
                        Database db = new Database(false, true);
                        db.ReadDwgFile(fileName,
                            System.IO.FileShare.ReadWrite,
                            false,
                            "");
                        ed.WriteMessage("正在对 " + row.Cells["SheetTitle"].Value.ToString() + " 签名...\n");
                        CommandSign.SignDB(db, signer, signItems, checkBox1.Checked);
                        ed.WriteMessage("正在对 " + row.Cells["SheetTitle"].Value.ToString() + " 删除签名...\n");
                        CommandSign.UnsignDB(db, unsignItems);
                        db.SaveAs(fileName, DwgVersion.Current);
                        CommandSign.PublishFile(fileName);
                    }
                    ed.WriteMessage("对 " + row.Cells["SheetTitle"].Value.ToString() + " 的操作完成！\n");
                }
                MessageBox.Show("完成！");
                ed.WriteMessage("全部签名完成！\n");
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
            finally
            {
                this.Close();
            }
        }

        private void btnAddFile_Click(object sender, EventArgs e)
        {
            //            string path = "";
            //            ProjectChooseForm pcf = new ProjectChooseForm(ref path, false);
            //            pcf.ShowDialog();
            if (this.cb_SubProNo.Text != "")
            {
                OpenFileDialog ofd = new OpenFileDialog();
                string dir = CommandSign.makeSubProDir(this.cb_ProNo.Text, this.cb_SubProNo.Text, this.cb_Major.Text);

                if (!(new DirectoryInfo(dir)).Exists)
                {
                    MessageBox.Show("目录不存在!");
                    return;
                }
                ofd.InitialDirectory = dir;
                /*                MessageBox.Show(CommandSign.path);*/
                ofd.Filter = "Drawing(*.dwg)|*.dwg";
                ofd.Multiselect = true;
                DialogResult dr = ofd.ShowDialog();
                if (dr == DialogResult.OK)
                {
                    

                    this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
                    int count = 0;
                    foreach (string fileName in ofd.FileNames)
                    {
                        if (Path.GetExtension(fileName) == ".dwg")
                        {
                            ++count;
                        }
                    }
                    this.progressBar1.Visible = true;
                    this.progressBar1.Maximum = count;
                    count = 0;
                    foreach (string file in ofd.FileNames)
                    {
                        string[] proFileName = file.Split('.');
                        string[] proID = proFileName[0].Split('\\');
                        UDCUserID uid = dt.udcList.Find(p => p.userName == cbsigner.Text);
                        UDCProjectID pid = uid.udcList.Find((p => p.projectID == cb_ProNo.Text));
                        UDCSubProjectID spid = pid.udcList.Find((p => p.subProjectID == cb_SubProNo.Text));
                        UDCProfession pro = spid.udcList.Find((p => p.profession ==  cb_Major.Text));
                        if (pro == null)
                        {
                            MessageBox.Show("无此专业");
                            this.progressBar1.Visible = false;
                            return;
                        }
                        //MessageBox.Show(proID[proID.Length - 1]);
                        //foreach (UDCDrawingID str in pro.udcList)
                        //{
                        //    MessageBox.Show(str.drawingID);
                        //}
                        
                        bool flag = AddFile(file);
                        MessageBox.Show(flag.ToString());
                        if (flag)
                        {
                            LockFile(file);
                            Competence competenceFile = new Competence();
                            //string str = "11001100110011001100110011001100110";
                            checkCompetence.SetDTCompetence(pro.competenceStr);
                            //MessageBox.Show(did.competenceStr.Length.ToString());
                            //MessageBox.Show(checkCompetence.getEnumTypeSize().ToString());

                            InitialCheckBox();
                            InitialCheckColumnStatus();
                            competenceFile.SetDTCompetence(pro.competenceStr);
                            //MessageBox.Show(str.Length.ToString());

                           // MessageBox.Show(competenceFile.getEnumTypeSize().ToString());
                            //MessageBox.Show(competenceFile.getCompetenceStr());
                            
                            signerCompetence.Add(competenceFile);
                        }
                        this.progressBar1.Increment(++count);
                    }
                    this.Cursor = System.Windows.Forms.Cursors.Default;
                    if (signerCompetence.Count > 0)
                    {
                        for (int i = 7; i < dataGridView.ColumnCount - 1; i++)
                        {
                            DataGridViewCell cell = dataGridView.Rows[signerCompetence.Count - 1].Cells[i];
                            if (!signerCompetence[signerCompetence.Count - 1].getCompetence((DLL.CONST.ConstCompetence)(i - 7)))
                            {
                                cell.Style.BackColor = Color.LightGray;
                            }
                        }
                    }

                        MessageBox.Show("导入完成!");
                    this.progressBar1.Visible = false;

                }

                //                 Editor ed = Tools.Editor;
                //                 PromptOpenFileOptions opts = new PromptOpenFileOptions("选择待签名文件");
                //                 opts.InitialDirectory = CommandSign.path;
                //                 opts.Filter = "Dwawing(*.dwg)|*.dwg";
                //                 PromptFileNameResult pr = ed.GetFileNameForOpen(opts);
                //                 if (pr.Status == PromptStatus.OK)
                //                 {
                //                     AddFile(pr.StringResult);
                //                     LockFile(pr.StringResult);
                //                 }
            }
            else
            {
                MessageBox.Show("未选择项目或子项目！");
            }
        }

        private void btnAddFiles_Click(object sender, EventArgs e)
        {
            try
            {
                //               string path = "";
                //               ProjectChooseForm pcf = new ProjectChooseForm(ref path, false);
                //                pcf.ShowDialog();
                //                 MessageBox.Show(CommandSign.path);
                //                 FolderDialog fd = new FolderDialog();
                //                 DialogResult dr = fd.DisplayDialog();

                if (this.cb_SubProNo.Text != "")
                {
                    this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
                    string rootFolderPath = CommandSign.makeSubProDir(this.cb_ProNo.Text, this.cb_SubProNo.Text, this.cb_Major.Text);

                    if (!(new DirectoryInfo(rootFolderPath)).Exists)
                    {
                        MessageBox.Show("目录不存在!");
                        this.Cursor = System.Windows.Forms.Cursors.Arrow;
                        return;
                    }

                    List<string> files = new List<string>();
                    CommandSign.GoThroughDirectory(rootFolderPath, ref files);
                    int count = 0;
                    foreach (string fileName in files)
                    {
                        if (Path.GetExtension(fileName) == ".dwg")
                        {
                            ++count;
                        }
                    }
                    this.progressBar1.Visible = true;
                    this.progressBar1.Maximum = count;
                    count = 0;
                    foreach (string fileName in files)
                    {
                        if (Path.GetExtension(fileName) == ".dwg")
                        {
                            string[] proFileName = fileName.Split('.');
                            string[] proID = proFileName[0].Split('\\');
                            UDCUserID uid = dt.udcList.Find(p => p.userName == cbsigner.Text);
                            UDCProjectID pid = uid.udcList.Find((p => p.projectID == cb_ProNo.Text));
                            UDCSubProjectID spid = pid.udcList.Find((p => p.subProjectID == cb_SubProNo.Text));
                            UDCProfession pro = spid.udcList.Find((p => p.profession == cb_Major.Text));
                            //MessageBox.Show(proID[proID.Length - 1]);
                            //foreach (UDCDrawingID str in pro.udcList)
                            //{
                            //    MessageBox.Show(str.drawingID);
                            //}
                            if (pro == null)
                            {
                                MessageBox.Show("查无此人");
                                continue;
                            }
                            if (AddFile(fileName))
                            {
                                LockFile(fileName);
                                Competence competenceFile = new Competence();
                                //string str = "11001100110011001100110011001100110";
                                checkCompetence.SetDTCompetence(pro.competenceStr);
                                //MessageBox.Show(did.competenceStr.Length.ToString());
                                //MessageBox.Show(checkCompetence.getEnumTypeSize().ToString());
                                competenceFile.SetDTCompetence(pro.competenceStr);
                                //MessageBox.Show(str.Length.ToString());
                                // MessageBox.Show(competenceFile.getEnumTypeSize().ToString());
                                //MessageBox.Show(competenceFile.getCompetenceStr());
                                signerCompetence.Add(competenceFile);
                            }
                            if (signerCompetence.Count > 0)
                            {
                                for (int i = 7; i < dataGridView.ColumnCount - 1; i++)
                                {
                                    DataGridViewCell cell = dataGridView.Rows[signerCompetence.Count - 1].Cells[i];
                                    if (!signerCompetence[signerCompetence.Count - 1].getCompetence((DLL.CONST.ConstCompetence)(i - 7)))
                                    {
                                        cell.Style.BackColor = Color.LightGray;
                                    }
                                }
                            }
                            this.progressBar1.Increment(++count);
                        }
                    }
                    InitialCheckBox();
                    InitialCheckColumnStatus();
                    MessageBox.Show("导入完成!");
                    this.progressBar1.Visible = false;
                    this.Cursor = System.Windows.Forms.Cursors.Default;
                }
                else
                {
                    MessageBox.Show("未选择项目或子项目！");
                }
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }


        /// <summary>
        /// 加锁
        /// </summary>
        /// <param name="fileName"></param>
        private void LockFile(string fileName)
        {
            try
            {
                FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read);
                locks.Add(new Pair(fileName, fs));
            }
            catch
            {
                MessageBox.Show(fileName + "正被打开，不能操作，已被跳过。");
            }
        }
        /// <summary>
        /// 解锁
        /// </summary>
        /// <param name="fileName"></param>
        private void UnLockFile(string fileName)
        {
            try
            {
                foreach (Pair p in locks)
                {
                    if (p.fileName == fileName)
                    {
                        p.fs.Close();
                        break;
                    }
                }
            }
            catch
            {
                MessageBox.Show(fileName + "在解锁文件时发生异常");
            }
        }


        private string GetAttributeByPosition(Database db, Point3d position)
        {
            using (Transaction trans = db.TransactionManager.StartTransaction())
            {
                BlockTable table = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                foreach (ObjectId recorfId in table)
                {
                    BlockTableRecord record = trans.GetObject(recorfId, OpenMode.ForRead) as BlockTableRecord;
                    if (CommandFrame.IsVersionType(record.Name))
                    {
                        ObjectIdCollection RefIds = record.GetBlockReferenceIds(true, true);
                        foreach (ObjectId RefId in RefIds)
                        {
                            BlockReference Reference = trans.GetObject(RefId, OpenMode.ForRead) as BlockReference;
                            AttributeCollection RefAttrisId = Reference.AttributeCollection;
                            foreach (ObjectId AttriId in RefAttrisId)
                            {
                                AttributeReference AttriRef = trans.GetObject(AttriId, OpenMode.ForRead) as AttributeReference;
                                if (AttriRef.Tag.EndsWith("SignPos") && (AttriRef.Position == position))
                                {
                                    return AttriRef.Tag.Substring(0, AttriRef.Tag.Length - "SignPos".Length);
                                }
                            }
                        }
                    }
                }
                return "";
            }
        }

        /// <summary>
        /// 解锁所有文件
        /// </summary>
        private void UnLockAllFiles()
        {
            for (int i = 0; i < dataGridView.Rows.Count; i++)
            {
                UnLockFile(dataGridView.Rows[i].Cells["FileName"].Value.ToString());
            }
        }

        /// <summary>
        /// 在datagridview控件里加入文件
        /// </summary>
        /// <param name="fileName"></param>
        public bool AddFile(string fileName)
        {
            if (signer == null)
            {
                //MessageBox.Show("请选择签名者！");
                //btnSelectSigner.PerformClick();
                if (signer == null)
                    return false;
            }
            //try
            //{
                Editor ed = Tools.Editor;
                //如果已经添加过此文件，无视
                foreach (DataGridViewRow row in dataGridView.Rows)
                {
                    string oldFileName = row.Cells["FileName"].Value.ToString();
                    if (oldFileName == fileName)
                    {
                        //MessageBox.Show(oldFileName + "已添加过，跳过！");
                        return false;
                    }
                    int oldLength = oldFileName.Length;
                    int newLength = fileName.Length;
                    if (oldFileName.Substring(0, oldLength - 5) == fileName.Substring(0, newLength - 5))
                    {
                        if (oldFileName[oldLength - 5] >= fileName[newLength - 5])
                        {
                            //MessageBox.Show(fileName + "版本过低，跳过");
                            return false;
                        }
                        if (oldFileName[oldLength - 5] < fileName[newLength - 5])
                        {
                            //MessageBox.Show("aaa");
                            UnLockFile(row.Cells["FileName"].Value.ToString());
                            dataGridView.Rows.Remove(row);
                            break;
                        }
                    }
                }

                //对于此文件，找到其中的图框并加入
                using (Database db = new Database(false, true))
                {
                    db.ReadDwgFile(fileName,
                        System.IO.FileShare.ReadWrite,
                        false,
                        "");

                    String strDbHashCode = Function_Hash.GetDwgHash(db);
                    int SuccessCount = 0;
                    int FailCount = 0;

                    using (Transaction trans = db.TransactionManager.StartTransaction())
                    {
                        BlockTable bt = trans.GetObject(db.BlockTableId, OpenMode.ForRead) as BlockTable;
                        foreach (ObjectId blockid in bt)
                        {
                            BlockTableRecord record = trans.GetObject(blockid, OpenMode.ForRead) as BlockTableRecord;
                            ObjectIdCollection blockRefIds = record.GetBlockReferenceIds(false, false);
                            foreach (ObjectId blockRefId in blockRefIds)
                            {
                                BlockReference blockRef = trans.GetObject(blockRefId, OpenMode.ForRead) as BlockReference;
                                Entity ent = trans.GetObject(blockRefId, OpenMode.ForRead) as Entity;
                                bool flag = true;
                                try
                                {
                                    Extents3d ext = blockRef.GeometricExtents;
                                }
                                catch
                                {
                                    flag = false;
                                }
                                if (flag)
                                {
                                    //Tools.WriteMessageWithReturn("Success Geo"+" Name=" + blockRef.Name+" BlockName=" + ent.BlockName);
                                    SuccessCount++;
                                }
                                else
                                {
                                    //Tools.WriteMessageWithReturn("Fail Geo" + " Name=" + blockRef.Name + " BlockName=" + ent.BlockName);
                                    FailCount++;
                                }
                            }
                        }
                        trans.Commit();
                    }
                    //Tools.WriteMessageWithReturn("Success=" + SuccessCount.ToString() + " Fail=" + FailCount.ToString());
                    using (Transaction trans = db.TransactionManager.StartTransaction())
                    {
                        BlockTable table = (BlockTable)trans.GetObject(db.BlockTableId, OpenMode.ForRead);
                        BlockTableRecord btr = trans.GetObject(table[BlockTableRecord.ModelSpace], OpenMode.ForWrite) as BlockTableRecord;
                        //先找到所有的签名块，取得它们的位置，方便后面检索哪些栏目已经被签过了
                        List<List<Point3d>> possList = new List<List<Point3d>>();
                        List<string> names = new List<string>();
                        List<Point3d> otherposs = new List<Point3d>();//其他人员签名位置

                        List<string> unsignItems = new List<string>();
                        BlockReference brFrame = null;
                        foreach (ObjectId blockId in table)
                        {
                            BlockTableRecord record = (BlockTableRecord)trans.GetObject(blockId, OpenMode.ForWrite);
                            if (CommandFrame.IsVersionType(record.Name))
                            {
                                ObjectIdCollection collection = record.GetBlockReferenceIds(true, true);
                                foreach (ObjectId frameId in collection)
                                {
                                    brFrame = trans.GetObject(frameId, OpenMode.ForWrite) as BlockReference;
                                    break;
                                }
                            }
                        }
                        if (brFrame == null)
                        {
                            MessageBox.Show("没图框");
                            return false;
                        }
                        if (brFrame.ExtensionDictionary == ObjectId.Null)
                        {
                            Tools.WriteMessageWithReturn("No Dictionary!");
                        }
                        else
                        {
                            DBDictionary dictionary = trans.GetObject(brFrame.ExtensionDictionary, OpenMode.ForRead) as DBDictionary;
                            AttributeCollection ac = brFrame.AttributeCollection;
                            foreach (ObjectId attrId in ac)
                            {
                                AttributeReference signAr = trans.GetObject(attrId, OpenMode.ForWrite) as AttributeReference;
                                if (signAr.Tag.EndsWith("SignPos"))
                                {
                                    string signItem = signAr.Tag.Substring(0, signAr.Tag.Length - "SignPos".Length);
                                    if (!dictionary.Contains(signItem))
                                    {
                                        continue;
                                    }
                                    ObjectId xRecId = dictionary.GetAt(signItem);
                                    Xrecord xRec = trans.GetObject(xRecId, OpenMode.ForRead) as Xrecord;
                                    ResultBuffer data = xRec.Data;
                                    bool flag1 = false, flag2 = false;
                                    string singleMd5 = Function_Hash.GetSingleMD5String(brFrame);
                                    foreach (TypedValue tv in data)
                                    {
                                        if (tv.Value.ToString() == singleMd5)
                                        {
                                            flag1 = true;
                                        }
                                        if (tv.Value.ToString() == strDbHashCode)
                                        {
                                            flag2 = true;
                                        }
                                    }
                                    if (flag1 && flag2)
                                    {
                                        string name = signAr.TextString;
                                        if (name == "hand")
                                        {
                                            foreach (ObjectId idtemp in ac)
                                            {
                                                AttributeReference artemp = trans.GetObject(idtemp, OpenMode.ForWrite) as AttributeReference;
                                                if (artemp.Tag == signItem)
                                                {
                                                    name = artemp.TextString;
                                                }
                                            }
                                        }
                                        int id = names.IndexOf(name);
                                        if (id != -1)
                                        {
                                            possList[id].Add(signAr.Position);
                                        }
                                        else
                                        {
                                            names.Add(name);
                                            List<Point3d> poss = new List<Point3d>();
                                            poss.Add(signAr.Position);
                                            possList.Add(poss);
                                        }
                                    }
                                    else
                                    {
                                        Tools.WriteMessageWithReturn("找到过期签名");
                                        unsignItems.Add(signItem);
                                    }
                                }
                            }
                        }

                        TJADRICD.CollaborativeDesignPlugin.CommandSign.UnsignDB(db, unsignItems);
                        db.SaveAs(db.Filename, DwgVersion.Current);
                        foreach (ObjectId blockId in table)
                        {
                            BlockTableRecord record = (BlockTableRecord)trans.GetObject(blockId, OpenMode.ForRead);

                            if (CommandFrame.IsVersionType(record.Name))  //如果此块定义名符合图框块名
                            {
                                ObjectIdCollection blockRefIds = record.GetBlockReferenceIds(true, true);  //取得此块定义所关联的所有块参照Id
                                foreach (ObjectId blockRefId in blockRefIds)
                                {
                                    string sheetTitle = "";
                                    string discipline = "";
                                    string stage = "";
                                    string sheetNo = "";
                                    string rev2 = "";
                                    string ApprovedBy = "";
                                    string ReviewedBy = "";
                                    string CheckedBy = "";
                                    string PrincipalInCharge1 = "";
                                    string PrincipalInCharge2 = "";
                                    string DisciplineResponsible1 = "";
                                    string DisciplineResponsible2 = "";
                                    string DesignedBy1 = "";
                                    string DesignedBy2 = "";
                                    string DrawnBy = "";
                                    string Architecture1 = "";
                                    string Architecture2 = "";
                                   // string Architecture3 = "";
                                    string Plumbing1 = "";
                                    string Plumbing2 = "";
                                   // string Plumbing3 = "";
                                    string HVAC1 = "";
                                    string HVAC2 = "";
                                   // string HVAC3 = "";
                                    string Electricity1 = "";
                                    string Electricity2 = "";
                                   // string Electricity3 = "";
                                    string Structure1 = "";
                                    string Structure2 = "";
                                    //string Structure3 = "";
                                    //string Structure4 = "";
                                    //string Structure5 = "";
                                    //string Structure6 = "";
                                    //string Structure7 = "";
                                    string Power1 = "";
                                    string Power2 = "";
                                    //string Power3 = "";
                                    string ELV1 = "";
                                    string ELV2 = "";
                                    //string ELV3 = "";

                                    BlockReference blockRef = (BlockReference)trans.GetObject(blockRefId, OpenMode.ForRead);
                                    AttributeCollection blockRefAttrs = blockRef.AttributeCollection;
                                    foreach (ObjectId attrRefId in blockRefAttrs)
                                    {
                                        AttributeReference attrRef = (AttributeReference)trans.GetObject(attrRefId, OpenMode.ForWrite);
                                        if (attrRef.Tag == "SheetTitleChinese")
                                        {
                                            sheetTitle = attrRef.TextString;
                                        }
                                        if (attrRef.Tag == "DisciplineChinese")
                                        {
                                            discipline = attrRef.TextString;
                                        }
                                        if (attrRef.Tag == "StageChinese")
                                        {
                                            stage = attrRef.TextString;
                                        }
                                        if (attrRef.Tag == "SheetNo")
                                        {
                                            sheetNo = attrRef.TextString;
                                        }
                                        if (attrRef.Tag == "Rev2")
                                        {
                                            rev2 = attrRef.TextString;
                                        }
                                        #region poss
                                        for (int i = 0; i < possList.Count; i++)
                                        {
                                            foreach (Point3d pos in possList[i])
                                            {
                                                if (attrRef.Position == pos)
                                                {
                                                    if (attrRef.Tag == "ApprovedBySignPos")
                                                    {
                                                        ApprovedBy = names[i];
                                                    }
                                                    if (attrRef.Tag == "ReviewedBySignPos")
                                                    {
                                                        ReviewedBy = names[i];
                                                    }
                                                    if (attrRef.Tag == "CheckedBySignPos")
                                                    {
                                                        CheckedBy = names[i];
                                                    }
                                                    if (attrRef.Tag == "PrincipalInCharge1SignPos")
                                                    {
                                                        PrincipalInCharge1 = names[i];
                                                    }
                                                    if (attrRef.Tag == "PrincipalInCharge2SignPos")
                                                    {
                                                        PrincipalInCharge2 = names[i];
                                                    }
                                                    if (attrRef.Tag == "DisciplineResponsible1SignPos")
                                                    {
                                                        DisciplineResponsible1 = names[i];
                                                    }
                                                    if (attrRef.Tag == "DisciplineResponsible2SignPos")
                                                    {
                                                        DisciplineResponsible2 = names[i];
                                                    }
                                                    if (attrRef.Tag == "DesignedBy1SignPos")
                                                    {
                                                        DesignedBy1 = names[i];
                                                    }
                                                    if (attrRef.Tag == "DesignedBy2SignPos")
                                                    {
                                                        DesignedBy2 = names[i];
                                                    }
                                                    if (attrRef.Tag == "DrawnBySignPos")
                                                    {
                                                        DrawnBy = names[i];
                                                    }
                                                    if (attrRef.Tag == "Architecture1SignPos")
                                                    {
                                                        Architecture1 = names[i];
                                                    }
                                                    if (attrRef.Tag == "Architecture2SignPos")
                                                    {
                                                        Architecture2 = names[i];
                                                    }
                                                    //if (attrRef.Tag == "Architecture3SignPos")
                                                    //{
                                                    //    Architecture3 = names[i];
                                                    //}
                                                    if (attrRef.Tag == "Plumbing1SignPos")
                                                    {
                                                        Plumbing1 = names[i];
                                                    }
                                                    if (attrRef.Tag == "Plumbing2SignPos")
                                                    {
                                                        Plumbing2 = names[i];
                                                    }
                                                    //if (attrRef.Tag == "Plumbing3SignPos")
                                                    //{
                                                    //    Plumbing3 = names[i];
                                                    //}
                                                    if (attrRef.Tag == "HVAC1SignPos")
                                                    {
                                                        HVAC1 = names[i];
                                                    }
                                                    if (attrRef.Tag == "HVAC2SignPos")
                                                    {
                                                        HVAC2 = names[i];
                                                    }
                                                    //if (attrRef.Tag == "HVAC3SignPos")
                                                    //{
                                                    //    HVAC3 = names[i];
                                                    //}
                                                    if (attrRef.Tag == "Electricity1SignPos")
                                                    {
                                                        Electricity1 = names[i];
                                                    }
                                                    if (attrRef.Tag == "Electricity2SignPos")
                                                    {
                                                        Electricity2 = names[i];
                                                    }
                                                    //if (attrRef.Tag == "Electricity3SignPos")
                                                    //{
                                                    //    Electricity3 = names[i];
                                                    //}
                                                    if (attrRef.Tag == "Structure1SignPos")
                                                    {
                                                        Structure1 = names[i];
                                                    }
                                                    if (attrRef.Tag == "Structure2SignPos")
                                                    {
                                                        Structure2 = names[i];
                                                    }
                                                    //if (attrRef.Tag == "Structure3SignPos")
                                                    //{
                                                    //    Structure3 = names[i];
                                                    //}
                                                    //if (attrRef.Tag == "Structure4SignPos")
                                                    //{
                                                    //    Structure4 = names[i];
                                                    //}
                                                    //if (attrRef.Tag == "Structure5SignPos")
                                                    //{
                                                    //    Structure5 = names[i];
                                                    //}
                                                    //if (attrRef.Tag == "Structure6SignPos")
                                                    //{
                                                    //    Structure6 = names[i];
                                                    //}
                                                    //if (attrRef.Tag == "Structure7SignPos")
                                                    //{
                                                    //    Structure7 = names[i];
                                                    //}
                                                    if (attrRef.Tag == "Power1SignPos")
                                                    {
                                                        Power1 = names[i];
                                                    }
                                                    if (attrRef.Tag == "Power2SignPos")
                                                    {
                                                        Power2 = names[i];
                                                    }
                                                    //if (attrRef.Tag == "Power3SignPos")
                                                    //{
                                                    //    Power3 = names[i];
                                                    //}
                                                    if (attrRef.Tag == "ELV1SignPos")
                                                    {
                                                        ELV1 = names[i];
                                                    }
                                                    if (attrRef.Tag == "ELV2SignPos")
                                                    {
                                                        ELV2 = names[i];
                                                    }
                                                    //if (attrRef.Tag == "ELV3SignPos")
                                                    //{
                                                    //    ELV3 = names[i];
                                                    //}
                                                }
                                            }
                                        }
                                        #endregion
                                    }
                                    int temp = dataGridView.Rows.Add(new object[] { false, "查看PDF文件", sheetTitle,
                                                discipline, stage, sheetNo, rev2,
                                                ApprovedBy, ReviewedBy, CheckedBy, PrincipalInCharge1, PrincipalInCharge2, DisciplineResponsible1, DisciplineResponsible2, DesignedBy1, DesignedBy2, DrawnBy,
                                                Architecture1, Architecture2, /*Architecture3,*/Plumbing1, Plumbing2, /*Plumbing3,*/ HVAC1, HVAC2,/* HVAC3,*/ Electricity1, Electricity2,/* Electricity3,*/ Structure1, Structure2,/* Structure3, Structure4, Structure5, Structure6, Structure7, */Power1, Power2,/* Power3,*/ ELV1, ELV2, /*ELV3
                                                , */fileName
                                    });
                                    return true; //只需要第一个图框就够了
                                }
                            }
                        }
                    }

                }
            //}
            //catch (System.Exception ex)
            //{
            //    MessageBox.Show("文件打开冲突");
            //    Tools.WriteMessageWithReturn(ex.ToString());
            //    //    Tools.WriteMessageWithReturn("由于文件打开冲突，跳过文件：" + fileName);                
            //}
            return false;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private void btnExclude_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < dataGridView.Rows.Count; i++)
            {
                if (dataGridView.Rows[i].Cells["Operation"].FormattedValue.ToString() == "True")
                {
                    UnLockFile(dataGridView.Rows[i].Cells["FileName"].Value.ToString());
                    dataGridView.Rows.RemoveAt(i);
                    signerCompetence.RemoveAt(i);
                    i--;
                }
            }
        }
        #region 选择角色
        private void QuickCheck(string cellName, bool state)
        {
            if (checkedInitialing) return;
            if (signer == null)
            {
                //MessageBox.Show("请选择签名者！");
                //btnSelectSigner.PerformClick();
                if (signer == null)
                    return;
            }

            for (int i = 0; i < dataGridView.Rows.Count; i++)
            {
                UpdateCellStatus(i, dataGridView.Columns.IndexOf(dataGridView.Columns[cellName]), state);
            }

        }
        private void cbDrawnBy_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("DrawnBy", ((CheckBox)sender).Checked);
        }

        private void cbApprovedBy_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("ApprovedBy", ((CheckBox)sender).Checked);
        }

        private void cbReviewedBy_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("ReviewedBy", ((CheckBox)sender).Checked);
        }

        private void cbCheckedBy_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("CheckedBy", ((CheckBox)sender).Checked);
        }

        private void cbPrincipalInCharge1_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("PrincipalInCharge1", ((CheckBox)sender).Checked);
        }

        private void cbPrincipalInCharge2_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("PrincipalInCharge2", ((CheckBox)sender).Checked);
        }

        private void cbDisciplineResponsible1_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("DisciplineResponsible1", ((CheckBox)sender).Checked);
        }

        private void cbDisciplineResponsible2_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("DisciplineResponsible2", ((CheckBox)sender).Checked);
        }

        private void cbDesignedBy1_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("DesignedBy1", ((CheckBox)sender).Checked);
        }

        private void cbDesignedBy2_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("DesignedBy2", ((CheckBox)sender).Checked);
        }
        #endregion

        private void dataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //InitialCheckStatus(e.RowIndex);
            int approvedByIndex = dataGridView.Columns.IndexOf(dataGridView.Columns["ApprovedBy"]);
            int CTBIndex = dataGridView.Columns.IndexOf(dataGridView.Columns["FileName"]);
            int CheckIndex = dataGridView.Columns.IndexOf(dataGridView.Columns["Operation"]);
            if (e.RowIndex > -1 && e.ColumnIndex == CheckIndex)
            {
                dataGridView.Rows[e.RowIndex].Cells["Operation"].Value = !(bool)(dataGridView.Rows[e.RowIndex].Cells["Operation"].Value);
            }
            
            if ((e.RowIndex > -1) && (e.ColumnIndex >= approvedByIndex) && (e.ColumnIndex != CTBIndex))
            {
                UpdateCellStatus(e.RowIndex, e.ColumnIndex);
                UpdateCheckStatus(e.ColumnIndex - 7);
            }
        }
        private void InitialCheckColumnStatus()
        {
            for (int i = 7; i < dataGridView.ColumnCount - 1; i++)
            {
                UpdateCheckStatus(i - 7);
            }
        }
        private bool CheckGridColumnStatus(int column,ref bool isBlank)
        {
            DataGridViewCell cell = dataGridView.Rows[0].Cells[column];
            
            string cellContent = cell.Value.ToString();
            isBlank = !(cellContent == "");
            for (int i = 1; i < dataGridView.Rows.Count; i++)
            {
                cell = dataGridView.Rows[i].Cells[column];
                if (cell.Value.ToString() != cellContent)
                {
                    return false;
                }
                
            }
            return true;
        }
        private void UpdateCheckStatus(int column)
        {
            DLL.CONST.ConstCompetence CompetenceEnumNumber = (DLL.CONST.ConstCompetence)column;
            bool isBlank = false;
            if (!CheckGridColumnStatus(column + 7 , ref isBlank)) isBlank = false;
            checkedInitialing = true;
            #region 复选框操作
            switch (CompetenceEnumNumber)
            {
                case DLL.CONST.ConstCompetence.VALIDATION:
                    cbApprovedBy.Checked = isBlank;
                    break;

                case DLL.CONST.ConstCompetence.AUDIT:
                    cbReviewedBy.Checked = isBlank;
                    break;
                case DLL.CONST.ConstCompetence.DESIGN_MANAGER1:
                    cbPrincipalInCharge1.Checked = isBlank;
                    break;

                case DLL.CONST.ConstCompetence.DESIGN_MANAGER2:
                    cbPrincipalInCharge2.Checked = isBlank;
                    break;
                case DLL.CONST.ConstCompetence.PROFESSIONAL_PERSON1:
                    cbDisciplineResponsible1.Checked = isBlank;
                    break;
                case DLL.CONST.ConstCompetence.PROFESSIONAL_PERSON2:
                    cbDisciplineResponsible2.Checked = isBlank;
                    break;
                case DLL.CONST.ConstCompetence.DESIGN1:
                    cbDesignedBy1.Checked = isBlank;
                    break;
                case DLL.CONST.ConstCompetence.DESIGN2:
                    cbDesignedBy2.Checked = isBlank;
                    break;
                case DLL.CONST.ConstCompetence.DRAW:
                    cbDrawnBy.Checked = isBlank;
                    break;
                case DLL.CONST.ConstCompetence.PROOF:
                    cbCheckedBy.Checked = isBlank;
                    break;
                case DLL.CONST.ConstCompetence.BUILD_COUNTERSIGN1:
                    cbArchitecture1.Checked = isBlank;
                    break;

                case DLL.CONST.ConstCompetence.BUILD_COUNTERSIGN2:
                    cbArchitecture2.Checked = isBlank;
                    break;
                case DLL.CONST.ConstCompetence.STRUCUTURE_COUNTERSIGN1:
                    cbStructure1.Checked = isBlank;
                    break;
                case DLL.CONST.ConstCompetence.STRUCUTURE_COUNTERSIGN2:
                    cbStructure2.Checked = isBlank;
                    break;
                case DLL.CONST.ConstCompetence.WATER_DRAIN_COUNTERSIGN1:
                    cbPlumbing1.Checked = isBlank;
                    break;
                case DLL.CONST.ConstCompetence.WATER_DRAIN_COUNTERSIGN2:
                    cbPlumbing2.Checked = isBlank;
                    break;
                case DLL.CONST.ConstCompetence.HVAC_COUNTERSIGN1:
                    cbHVAC1.Checked = isBlank;
                    break;

                case DLL.CONST.ConstCompetence.HVAC_COUNTERSIGN2:
                    cbHVAC2.Checked = !cbHVAC2.Checked;
                    break;
                case DLL.CONST.ConstCompetence.STRONG_ELECTRIC_COUNTERSIGN1:
                    cbElectricity1.Checked = !cbElectricity1.Checked;
                    break;
                case DLL.CONST.ConstCompetence.STRONG_ELECTRIC_COUNTERSIGN2:
                    cbElectricity2.Checked = !cbElectricity2.Checked;
                    break;
                case DLL.CONST.ConstCompetence.POWER_COUNTERSIGN1:
                    cbPower1.Checked = !cbPower1.Checked;
                    break;
                case DLL.CONST.ConstCompetence.POWER_COUNTERSIGN2:
                    cbPower2.Checked = !cbPower2.Checked;
                    break;
                case DLL.CONST.ConstCompetence.WEAK_ELECTRIC_COUNTERSIGN1:
                    cbELV1.Checked = !cbELV1.Checked;
                    break;
                case DLL.CONST.ConstCompetence.WEAK_ELECTRIC_COUNTERSIGN2:
                    cbELV2.Checked = !cbELV2.Checked;
                    break;
                default:
                    break;
            }

            #endregion
            checkedInitialing = false;
        }
        
        //private void InitialCheckStatus(int row)
        //{
        //    if (checkedRows == row) return;
        //    checkedRows = row;
        //    bool[] competence = signerCompetence[row].getCompetence();
        //    checkedInitialing = true;
        //    #region 复选框操作
        //    cbApprovedBy.Enabled = false;
        //    cbApprovedBy.Checked = false;
        //    if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.VALIDATION)])
        //    {
        //        cbApprovedBy.Enabled = true;
        //    }
        //    cbReviewedBy.Enabled = false;
        //    cbReviewedBy.Checked = false;
        //    if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.AUDIT)])
        //    {
        //        cbReviewedBy.Enabled = true;
        //    }
        //    cbPrincipalInCharge1.Enabled = false;
        //    cbPrincipalInCharge1.Checked = false;
        //    if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.DESIGN_MANAGER1)])
        //    {
        //        cbPrincipalInCharge1.Enabled = true;
        //    }
        //    cbPrincipalInCharge2.Enabled = false;
        //    cbPrincipalInCharge2.Checked = false;
        //    if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.DESIGN_MANAGER2)])
        //    {
        //        cbPrincipalInCharge2.Enabled = true;
        //    }
        //    cbDisciplineResponsible1.Enabled = false;
        //    cbDisciplineResponsible1.Checked = false;
        //    if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.PROFESSIONAL_PERSON1)])
        //    {
        //        cbDisciplineResponsible1.Enabled = true;
        //    }
        //    cbDisciplineResponsible2.Enabled = false;
        //    cbDisciplineResponsible2.Checked = false;
        //    if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.PROFESSIONAL_PERSON2)])
        //    {
        //        cbDisciplineResponsible2.Enabled = true;
        //    }
        //    cbDesignedBy1.Enabled = false;
        //    cbDesignedBy1.Checked = false;
        //    if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.DESIGN1)])
        //    {
        //        cbDesignedBy1.Enabled = true;
        //    }
        //    cbDesignedBy2.Enabled = false;
        //    cbDesignedBy2.Checked = false;
        //    if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.DESIGN2)])
        //    {
        //        cbDesignedBy2.Enabled = true;
        //    }
        //    cbDrawnBy.Enabled = false;
        //    cbDrawnBy.Checked = false;
        //    if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.DRAW)])
        //    {
        //        cbDrawnBy.Enabled = true;
        //    }
        //    cbCheckedBy.Enabled = false;
        //    cbCheckedBy.Checked = false;
        //    if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.PROOF)])
        //    {
        //        cbCheckedBy.Enabled = true;
        //    }
        //    cbArchitecture1.Enabled = false;
        //    cbArchitecture1.Checked = false;
        //    if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.BUILD_COUNTERSIGN1)])
        //    {
        //        cbArchitecture1.Enabled = true;
        //    }
        //    cbArchitecture2.Enabled = false;
        //    cbArchitecture2.Checked = false;
        //    if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.BUILD_COUNTERSIGN2)])
        //    {
        //        cbArchitecture2.Enabled = true;
        //    }
        //    cbStructure1.Enabled = false;
        //    cbStructure1.Checked = false;
        //    if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.STRUCUTURE_COUNTERSIGN1)])
        //    {
        //        cbStructure1.Enabled = true;
        //    }
        //    cbPlumbing1.Enabled = false;
        //    cbPlumbing1.Checked = false;
        //    if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.WATER_DRAIN_COUNTERSIGN1)])
        //    {
        //        cbPlumbing1.Enabled = true;
        //    }
        //    cbPlumbing2.Enabled = false;
        //    cbPlumbing2.Checked = false;
        //    if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.WATER_DRAIN_COUNTERSIGN2)])
        //    {
        //        cbPlumbing2.Enabled = true;
        //    }
        //    cbHVAC1.Enabled = false;
        //    cbHVAC1.Checked = false;
        //    if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.HVAC_COUNTERSIGN1)])
        //    {
        //        cbHVAC1.Enabled = true;
        //    }
        //    cbHVAC2.Enabled = false;
        //    cbHVAC2.Checked = false;
        //    if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.HVAC_COUNTERSIGN2)])
        //    {
        //        cbHVAC2.Enabled = true;
        //    }
        //    cbElectricity1.Enabled = false;
        //    cbElectricity1.Checked = false;
        //    if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.STRONG_ELECTRIC_COUNTERSIGN1)])
        //    {
        //        cbElectricity1.Enabled = true;
        //    }
        //    cbElectricity2.Enabled = false;
        //    cbElectricity2.Checked = false;
        //    if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.STRONG_ELECTRIC_COUNTERSIGN2)])
        //    {
        //        cbElectricity2.Enabled = true;
        //    }
        //    cbPower1.Enabled = false;
        //    cbPower1.Checked = false;
        //    if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.POWER_COUNTERSIGN1)])
        //    {
        //        cbPower1.Enabled = true;
        //    }
        //    cbPower2.Enabled = false;
        //    cbPower2.Checked = false;
        //    if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.POWER_COUNTERSIGN2)])
        //    {
        //        cbPower2.Enabled = true;
        //    }
        //    cbELV1.Enabled = false;
        //    cbELV1.Checked = false;
        //    if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.WEAK_ELECTRIC_COUNTERSIGN1)])
        //    {
        //        cbELV1.Enabled = true;
        //    }
        //    cbELV2.Enabled = false;
        //    cbELV2.Checked = false;
        //    if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.WEAK_ELECTRIC_COUNTERSIGN2)])
        //    {
        //        cbELV2.Enabled = true;
        //    }
        //    #endregion
        //    checkedInitialing = false;
        //}
        private void UpdateCellStatus(int row, int col)
        {
            if (signer == null)
            {
                //MessageBox.Show("请选择签名者！");
                //btnSelectSigner.PerformClick();
                if (signer == null)
                    return;
            }
            DataGridViewCell cell = dataGridView.Rows[row].Cells[col];
            cell.Selected = false;
           // MessageBox.Show(row.ToString());
           // MessageBox.Show(signerCompetence[row].getCompetenceStr());
           // MessageBox.Show(Enum.GetName(typeof(DLL.CONST.ConstCompetence),col - 7));
            if (signerCompetence[row].getCompetence((DLL.CONST.ConstCompetence)(col - 7)))
            {
                if (cell.Value.ToString() == "")
                {
                    //UpdateSingleCheckStatus(col - 7);
                    cell.Value = signer;
                    cell.Style.BackColor = Color.LightGreen;
                }
                else
                {
                    //是自己的签名，可删
                    cell.Value = "";
                    //UpdateSingleCheckStatus(col - 7);
                    cell.Style.BackColor = Color.White;
                }
            }
            //else
            //{

            //        //已有别人签名，冲突
            //        cell.Style.BackColor = Color.Red;



            //}
        }

        private void UpdateCellStatus(int row, int col, bool status)
        {
            DataGridViewCell cell = dataGridView.Rows[row].Cells[col];
            cell.Selected = false;
              if (signerCompetence[row].getCompetence((DLL.CONST.ConstCompetence)(col - 7)))
            {
            if (status == true)
            {
                //check checkbox
                if (cell.Value.ToString() != "")
                {
                    cell.Value = "";
                    cell.Style.BackColor = Color.White;
                }
                else
                {
                    cell.Value = signer;
                    cell.Style.BackColor = Color.LightGreen;
                }
                
                //if (cell.Value.ToString() != "" && cell.Value.ToString() != signer)
                //{
                    //已有别人签名，冲突
                //    cell.Style.BackColor = Color.Red;
                //}

            }
            else
            {
                //uncheck checkbox
                if (cell.Value.ToString() != "")
                {
                    //if (cell.Value.ToString() != signerCompetence[row].getSignerName((DLL.CONST.ConstCompetence)(col - 7)))
                    //{
                    //    //是别人签的，不应删掉
                    //    cell.Style.BackColor = Color.LightYellow;
                    //}
                    //else
                    //{
                        //自己签的，可以删掉
                        cell.Style.BackColor = Color.White;
                        cell.Value = "";
                    //}
                }
                else 
                {
                    cell.Value = signer;
                    cell.Style.BackColor = Color.White;
                }
            }
                  }
        }

        private void SignControl_FormClosing(object sender, FormClosingEventArgs e)
        {
            UnLockAllFiles();
        }

        private void cbStructure5_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("Structure5", ((CheckBox)sender).Checked);

        }

        private void cbStructure4_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("Structure4", ((CheckBox)sender).Checked);
        }

        private void cbStructrue6_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("Structure6", ((CheckBox)sender).Checked);
        }

        private void cbArchitecture1_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("Architecture1", ((CheckBox)sender).Checked);
        }

        private void cbArchitecture2_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("Architecture2", ((CheckBox)sender).Checked);
        }

        private void cbArchitecture3_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("Architecture3", ((CheckBox)sender).Checked);
        }

        private void cbStructure1_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("Structure1", ((CheckBox)sender).Checked);
        }

        private void cbStructure2_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("Structure2", ((CheckBox)sender).Checked);
        }

        private void cbStructure3_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("Structure3", ((CheckBox)sender).Checked);
        }

        private void cbStructure7_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("Structure7", ((CheckBox)sender).Checked);
        }

        private void cbPlumbing1_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("Plumbing1", ((CheckBox)sender).Checked);
        }

        private void cbPlumbing2_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("Plumbing2", ((CheckBox)sender).Checked);
        }

        private void cbPlumbing3_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("Plumbing3", ((CheckBox)sender).Checked);
        }

        private void cbHVAC1_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("HVAC1", ((CheckBox)sender).Checked);
        }

        private void cbHVAC2_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("HVAC2", ((CheckBox)sender).Checked);
        }

        private void cbHVAC3_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("HVAC3", ((CheckBox)sender).Checked);
        }

        private void cbElectricity1_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("Electricity1", ((CheckBox)sender).Checked);
        }

        private void cbElectricity2_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("Electricity2", ((CheckBox)sender).Checked);
        }

        private void cbElectricity3_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("Electricity3", ((CheckBox)sender).Checked);
        }

        private void cbPower1_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("Power1", ((CheckBox)sender).Checked);
        }
        private void cbPower2_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("Power2", ((CheckBox)sender).Checked);
        }
        private void groupBox5_Enter(object sender, EventArgs e)
        {
        }

        private void cbPower3_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("Power3", ((CheckBox)sender).Checked);
        }

        private void cbELV1_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("ELV1", ((CheckBox)sender).Checked);
        }

        private void cbELV2_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("ELV2", ((CheckBox)sender).Checked);
        }

        private void cbELV3_CheckedChanged(object sender, EventArgs e)
        {
            QuickCheck("ELV3", ((CheckBox)sender).Checked);
        }

        private string GetPDFByDWG(string dwgFilePath)
        {
            if (!File.Exists(dwgFilePath))
            {
                return String.Empty;
            }
            FileInfo dwgFile = new FileInfo(dwgFilePath);
            DirectoryInfo dir_displine = dwgFile.Directory;
            DirectoryInfo dir_tz = dir_displine.Parent;
            DirectoryInfo dir_common = dir_tz.Parent;
            Char[] seperator = { '.' };
            String[] file_names = dwgFile.Name.Split(seperator);
            String pdfPath = dir_common.FullName + @"\PDF\" + file_names.First() + ".pdf";
            return pdfPath;
        }

        private void dataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == dataGridView.Columns["PDFView"].Index)
            {
                string pdfFilePath = GetPDFByDWG(dataGridView.Rows[e.RowIndex].Cells["FileName"].Value.ToString());
                if (!File.Exists(pdfFilePath))
                {
                    MessageBox.Show("PDF文件不存在！ 路径：" + pdfFilePath);
                }
                else
                {
                    System.Diagnostics.Process.Start(pdfFilePath);
                }
            }
        }

        private void btn_quickSign_Click(object sender, EventArgs e)
        {
            CommandSign.QuickSignEx();
        }

        private void cb_ProNo_SelectedIndexChanged(object sender, EventArgs e)
        {
            //string fatherpath = "";
            //foreach (string webPath in Config.ProjectPath)
            //{
            //    DirectoryInfo Dir_Web = new DirectoryInfo(webPath);
            //    DirectoryInfo[] Dir_Pros = Dir_Web.GetDirectories();
            //    foreach (DirectoryInfo Dir_Pro in Dir_Pros)
            //    {
            //        if (Dir_Pro.Name == this.cb_ProNo.Text)
            //        {
            //            fatherpath = webPath;
            //        }
            //    }
            //}
            this.cb_SubProNo.Text = "";
            ////            this.cb_Major.Items.Clear();
            //DirectoryInfo Dir_Web2 = new DirectoryInfo(fatherpath + this.cb_ProNo.Text + "\\");
            //DirectoryInfo[] Dir_Pros2 = Dir_Web2.GetDirectories();
            //foreach (DirectoryInfo Dir_Pro in Dir_Pros2)
            //{
            this.cb_SubProNo.Items.Clear();
            UDCUserID uid = dt.udcList.Find(p => p.userName == cbsigner.Text);
            UDCProjectID pid = uid.udcList.Find((p => p.projectID == cb_ProNo.Text));
            foreach (UDCSubProjectID spid in pid.udcList)
            {
                this.cb_SubProNo.Items.Add(spid.subProjectID);
            }

            this.cb_Major.Items.Clear();
            //}
        }

        private void cb_SubProNo_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.cb_Major.Items.Clear();
            this.cb_Major.Text = "";
            UDCUserID uid = dt.udcList.Find(p => p.userName == cbsigner.Text);
            UDCProjectID pid = uid.udcList.Find((p => p.projectID == cb_ProNo.Text));
            UDCSubProjectID spid = pid.udcList.Find((p => p.subProjectID == cb_SubProNo.Text));
            foreach (UDCProfession pro in spid.udcList)
            {
                this.cb_Major.Items.Add(pro.profession);
            }

            
            //             string fatherpath = "";
            //             foreach (string webPath in Convention.WebDirectorys)
            //             {
            //                 DirectoryInfo Dir_Web = new DirectoryInfo(webPath);
            //                 DirectoryInfo[] Dir_Pros = Dir_Web.GetDirectories();
            //                 foreach (DirectoryInfo Dir_Pro in Dir_Pros)
            //                 {
            //                     if (Dir_Pro.Name == this.cb_ProNo.Text)
            //                     {
            //                         fatherpath = webPath;
            //                     }
            //                 }
            //             }
            //             this.cb_Major.Items.Clear();
            //             DirectoryInfo Dir_Web2 = new DirectoryInfo(fatherpath + this.cb_ProNo.Text + "\\" + this.cb_SubProNo.Text + "\\Common\\TZ\\");
            //             DirectoryInfo[] Dir_Pros2 = Dir_Web2.GetDirectories();
            //             foreach (DirectoryInfo Dir_Pro in Dir_Pros2)
            //             {
            //                 if (Dir_Pro.Name != "PDF")
            //                 {
            //                     string major = Dir_Pro.Name;
            //                     switch (major)
            //                     {
            //                         case "JZ":
            //                             major = "建筑";
            //                             break;
            //                         case "JG":
            //                             major = "结构";
            //                             break;
            //                         case "GPS":
            //                             major = "给排水";
            //                             break;
            //                         case "DL":
            //                             major = "电力";
            //                             break;
            //                         case "NT":
            //                             major = "暖通";
            //                             break;
            //                         case "QD":
            //                             major = "强电";
            //                             break;
            //                         case "RD":
            //                             major = "弱电";
            //                             break;
            //                         default:
            //                             break;
            //                     }
            //                     this.cb_Major.Items.Add(major);
            //                 }
            //             }
        }

        private void CommissionButton_Click(object sender, EventArgs e)
        {
            FormCommission formCommission = new FormCommission(userID, this.cbsigner.Text);
            formCommission.ShowDialog();
        }

        private void SignAnotherbutton_Click(object sender, EventArgs e)
        {
            if (this.cb_ProNo.Text.Equals("") || this.cb_SubProNo.Text.Equals(""))
            {
                MessageBox.Show("请选择项目和子项目号");
            } 
            else
            {
                SignAnother formSignAnother = new SignAnother(userID, this.cb_ProNo.Text, this.cb_SubProNo.Text);
                formSignAnother.Owner = this;
                formSignAnother.ShowDialog();
            }
            
        }

        private void ChangePwd_Click(object sender, EventArgs e)
        {
            ChangePwd changPwd = new ChangePwd(false, signer);
            changPwd.ShowDialog();
        }

        private void ChangeCommissionPwd_Click(object sender, EventArgs e)
        {
            ChangePwd changPwd = new ChangePwd(true, signer);
            changPwd.ShowDialog();
        }

        private void CancelSignAnotherBt_Click(object sender, EventArgs e)
        {
            signer = userName;
            CommissionName.Text = "无";
        }

        private void CancelCommissionBt_Click(object sender, EventArgs e)
        {
            CancelCommission formCancelCommission = new CancelCommission(userID, this.cbsigner.Text);
            formCancelCommission.ShowDialog();
        }

        private void InterfaceInput_Click(object sender, EventArgs e)
        {
            
            DrawingInput di = new DrawingInput();
            di.Show();
        }

        private void cbsigner_SelectedIndexChanged(object sender, EventArgs e)
        {
            signer = cbsigner.Text;
            checkedInitialing = false;
            checkCompetence.InitComStr();
            InitialCheckBox();
            for (int i = 0; i < dataGridView.Rows.Count; i++)
            {
                    UnLockFile(dataGridView.Rows[i].Cells["FileName"].Value.ToString());
                    dataGridView.Rows.RemoveAt(i);
                    signerCompetence.RemoveAt(i);
                    i--;
 
            }
            this.cb_ProNo.Items.Clear();
            this.cb_ProNo.Text = "";
            UDCUserID uid = dt.udcList.Find(p => p.userName == cbsigner.Text);
            if (uid != null)
            {
                foreach (UDCProjectID pid in uid.udcList)
                {
                    this.cb_ProNo.Items.Add(pid.projectID);
                }
            }
            this.cb_SubProNo.Items.Clear();
            this.cb_Major.Items.Clear();
        }

        private void InitialCheckBox()
        {
            checkedInitialing = true;
            
            bool[] competence = checkCompetence.getCompetence();
            //string str = "";
            //foreach (bool ch in competence)
            //{
            //    str = str + (Convert.ToInt32(ch)).ToString();
            //}
            //MessageBox.Show(str);
            #region 复选框操作
            cbApprovedBy.Enabled = false;
            cbApprovedBy.Checked = false;
            if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.VALIDATION)])
            {
                cbApprovedBy.Enabled = true;
            }
            cbReviewedBy.Enabled = false;
            cbReviewedBy.Checked = false;
            if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.AUDIT)])
            {
                cbReviewedBy.Enabled = true;
            }
            cbPrincipalInCharge1.Enabled = false;
            cbPrincipalInCharge1.Checked = false;
            if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.DESIGN_MANAGER1)])
            {
                cbPrincipalInCharge1.Enabled = true;
            }
            cbPrincipalInCharge2.Enabled = false;
            cbPrincipalInCharge2.Checked = false;
            if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.DESIGN_MANAGER2)])
            {
                cbPrincipalInCharge2.Enabled = true;
            }
            cbDisciplineResponsible1.Enabled = false;
            cbDisciplineResponsible1.Checked = false;
            if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.PROFESSIONAL_PERSON1)])
            {
                cbDisciplineResponsible1.Enabled = true;
            }
            cbDisciplineResponsible2.Enabled = false;
            cbDisciplineResponsible2.Checked = false;
            if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.PROFESSIONAL_PERSON2)])
            {
                cbDisciplineResponsible2.Enabled = true;
            }
            cbDesignedBy1.Enabled = false;
            cbDesignedBy1.Checked = false;
            if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.DESIGN1)])
            {
                cbDesignedBy1.Enabled = true;
            }
            cbDesignedBy2.Enabled = false;
            cbDesignedBy2.Checked = false;
            if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.DESIGN2)])
            {
                cbDesignedBy2.Enabled = true;
            }
            cbDrawnBy.Enabled = false;
            cbDrawnBy.Checked = false;
            if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.DRAW)])
            {
                cbDrawnBy.Enabled = true;
            }
            cbCheckedBy.Enabled = false;
            cbCheckedBy.Checked = false;
            if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.PROOF)])
            {
                cbCheckedBy.Enabled = true;
            }
            cbArchitecture1.Enabled = false;
            cbArchitecture1.Checked = false;
            if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.BUILD_COUNTERSIGN1)])
            {
                cbArchitecture1.Enabled = true;
            }
            cbArchitecture2.Enabled = false;
            cbArchitecture2.Checked = false;
            if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.BUILD_COUNTERSIGN2)])
            {
                cbArchitecture2.Enabled = true;
            }
            cbStructure1.Enabled = false;
            cbStructure1.Checked = false;
            if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.STRUCUTURE_COUNTERSIGN1)])
            {
                cbStructure1.Enabled = true;
            }
            cbStructure2.Enabled = false;
            cbStructure2.Checked = false;
            if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.STRUCUTURE_COUNTERSIGN2)])
            {
                cbStructure2.Enabled = true;
            }
            cbPlumbing1.Enabled = false;
            cbPlumbing1.Checked = false;
            if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.WATER_DRAIN_COUNTERSIGN1)])
            {
                cbPlumbing1.Enabled = true;
            }
            cbPlumbing2.Enabled = false;
            cbPlumbing2.Checked = false;
            if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.WATER_DRAIN_COUNTERSIGN2)])
            {
                cbPlumbing2.Enabled = true;
            }
            cbHVAC1.Enabled = false;
            cbHVAC1.Checked = false;
            if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.HVAC_COUNTERSIGN1)])
            {
                cbHVAC1.Enabled = true;
            }
            cbHVAC2.Enabled = false;
            cbHVAC2.Checked = false;
            if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.HVAC_COUNTERSIGN2)])
            {
                cbHVAC2.Enabled = true;
            }
            cbElectricity1.Enabled = false;
            cbElectricity1.Checked = false;
            if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.STRONG_ELECTRIC_COUNTERSIGN1)])
            {
                cbElectricity1.Enabled = true;
            }
            cbElectricity2.Enabled = false;
            cbElectricity2.Checked = false;
            if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.STRONG_ELECTRIC_COUNTERSIGN2)])
            {
                cbElectricity2.Enabled = true;
            }
            cbPower1.Enabled = false;
            cbPower1.Checked = false;
            if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.POWER_COUNTERSIGN1)])
            {
                cbPower1.Enabled = true;
            }
            cbPower2.Enabled = false;
            cbPower2.Checked = false;
            if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.POWER_COUNTERSIGN2)])
            {
                cbPower2.Enabled = true;
            }
            cbELV1.Enabled = false;
            cbELV1.Checked = false;
            if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.WEAK_ELECTRIC_COUNTERSIGN1)])
            {
                cbELV1.Enabled = true;
            }
            cbELV2.Enabled = false;
            cbELV2.Checked = false;
            if (competence[Convert.ToInt32(DLL.CONST.ConstCompetence.WEAK_ELECTRIC_COUNTERSIGN2)])
            {
                cbELV2.Enabled = true;
            }
            #endregion
            checkedInitialing = false;
        }

        private void cb_Major_SelectedIndexChanged(object sender, EventArgs e)
        {

        }



    }
}
